using System;
using System.Collections.Generic;
using System.Text;

using Weazel.Microblaze.Simulator.Engine;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    public class Bgei
      : ConditionalBranchInstruction
    {
        private enum BgeiInstructionKind
        {
            None,
            bgei,
            bgeid
        }

        private BgeiInstructionKind kind;

        public override int CycleCount
        {
            get
            {
                if (BranchStatus == BranchInstructionCycleCountStatus.BranchTaken)
                    return 1;
                else
                    return kind == BgeiInstructionKind.bgeid ? 2 : 3;
            }
        }

        public Bgei()
            : base("bgei")
        {
        }

        public override void Set(uint address, uint value)
        {
            base.Set(address, value);

            kind =
              (DestinationRegister == 0x05) ? BgeiInstructionKind.bgei :
              (DestinationRegister == 0x15) ? BgeiInstructionKind.bgeid :
              BgeiInstructionKind.None;

            if (kind == BgeiInstructionKind.None)
                throw new UnknownInstructionException(value);
        }

        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {
            // note use of int
            int sa = (int)MicroblazeComponent.ReadRegister(SourceRegisterA);

            if (sa >= 0)
            {
                MicroblazeComponent.Pc = MicroblazeComponent.Pc + GetImmediateValue(MicroblazeComponent);
                BranchStatus = BranchInstructionCycleCountStatus.BranchTaken;

                if (kind == BgeiInstructionKind.bgeid)
                    MicroblazeComponent.DelayedBranchActive = true;
            }
            else
            {
                MicroblazeComponent.Pc += 4;
                BranchStatus = BranchInstructionCycleCountStatus.BranchNotTaken;
            }
        }

        public override string ToString()
        {
            return string.Format("{0} r{1}, {2}",
              kind,
              SourceRegisterA,
              ImmediateValue
            );
        }
    }
}
